import {Modal} from 'antd';
import 'whatwg-fetch';

function apiWarning (err) {
    console.log('接口异常(showWarning)：', err.toString());
    Modal.info({
        title: '错误',
        content: '数据异常，请尝试刷新页面',
        okText: '刷新',
        onOk() {
            location.reload();
        }
    });
}

function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        setTimeout(() => {
            input.setSelectionRange(selectionStart, selectionEnd);

        }, 10)
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

/**
 * 是否Pc端
 * @returns {boolean}
 */
function isPC() {
    if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){
        return false;
    }
    return true;
}

/**
 * dom对象的offset
 * @param domObj
 * @returns {{}}
 */
function domOffset(domObj){
    let result = {}
    result.left = domObj.offsetLeft;
    result.top = domObj.offsetTop;
    let current = domObj.offsetParent;
    while(current != null){
        result.left += current.offsetLeft;
        result.top += current.offsetTop;
        current = current.offsetParent;
    }
    return result;
}

/**
 * fetch包装函数
 * @param input
 * @param opts
 * @returns {Promise.<*>}
 */
function fetchWrapper (input, opts) {//定义新的fetch方法，封装原有的fetch方法
    var fetchPromise = fetch(input, opts);
    var timeoutPromise = new Promise(function (resolve, reject) {
        setTimeout(() => {
            reject(new Error(`\nfetch timeout；\napi: ${input}`))
        }, opts.timeout || 30000)
    });
    return Promise.race([fetchPromise, timeoutPromise]);
}

function yyFetch(input, opts) {
    let baseData = window.processSession.baseData;
    opts.headers = {
        'thd_appId': 'yongyoussc',
        'thd_secureKey': 'ssc_fi_dev',
        'thd_tenantId': baseData.tenantId,
        'thd_userId': baseData.userCode,
        ...opts.headers
    }
    return fetchWrapper(input, opts);
}

function yyFetchJson(input, opts) {
    return yyFetch(input, opts).then(function (res) {
        return res.json().then(function(json) {
            return json
        }).catch((err) => {
            console.error('fetch error',  err, '接口api:', input, opts);
        })
    })
}

function bytesToSize(bytes) {
    if (bytes === 0) return '0 B';
    var k = 1000,
        sizes = ['字节', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));

    return Number((bytes / Math.pow(k, i)).toFixed(2)).toString() + sizes[i];
}

export {setSelectionRange, isPC, domOffset, fetchWrapper as fetch, yyFetch, yyFetchJson, apiWarning, bytesToSize}